using Microsoft.AspNetCore.Mvc;
using SG3L_RAG.Application.Interfaces;
using SG3L_RAG.Domain.Entities;

namespace SG3L_RAG.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ConversationsController : ControllerBase
    {

        private readonly IConversationService _conversationService;

        public ConversationsController(IConversationService conversationService)
        {
            _conversationService = conversationService;
        }

        /// <summary>
        /// 获取用户收藏的会话集合
        /// </summary>
        [HttpGet("user/{userId}/collected")]
        public async Task<ActionResult<IEnumerable<Conversation>>> GetCollectedConversations(Guid userId)
        {
            var conversations = await _conversationService.GetCollectedByUserIdAsync(userId);
            return Ok(conversations);
        }

        /// <summary>
        /// 获取所有对话
        /// </summary>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Conversation>>> GetAllConversations()
        {
            var conversations = await _conversationService.GetAllAsync();
            return Ok(conversations);
        }

        /// <summary>
        /// 分页获取所有对话
        /// </summary>
        [HttpGet("paged")]
        public async Task<ActionResult<PagedResult<Conversation>>> GetAllConversationsPaged(
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 12)
        {
            var pagedResult = await _conversationService.GetAllPagedAsync(page, pageSize);
            return Ok(pagedResult);
        }

        /// <summary>
        /// 根据ID获取对话
        /// </summary>
        [HttpGet("{id}")]
        public async Task<ActionResult<Conversation>> GetConversation(Guid id)
        {
            var conversation = await _conversationService.GetByIdAsync(id);
            if (conversation == null)
            {
                return NotFound($"对话 {id} 不存在");
            }
            return Ok(conversation);
        }

        /// <summary>
        /// 根据用户ID获取对话列表
        /// </summary>
        [HttpGet("user/{userId}")]
        public async Task<ActionResult<IEnumerable<Conversation>>> GetConversationsByUser(Guid userId)
        {
            var conversations = await _conversationService.GetByUserIdAsync(userId);
            return Ok(conversations);
        }

        /// <summary>
        /// 分页获取用户对话列表
        /// </summary>
        [HttpGet("user/{userId}/paged")]
        public async Task<ActionResult<PagedResult<Conversation>>> GetConversationsByUserPaged(
            Guid userId,
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 12)
        {
            var pagedResult = await _conversationService.GetByUserIdPagedAsync(userId, page, pageSize);
            return Ok(pagedResult);
        }

        /// <summary>
        /// 获取用户最新的对话
        /// </summary>
        [HttpGet("user/{userId}/latest")]
        public async Task<ActionResult<Conversation>> GetLatestConversation(Guid userId)
        {
            var conversation = await _conversationService.GetLatestByUserIdAsync(userId);
            if (conversation == null)
            {
                return NotFound($"用户 {userId} 没有对话");
            }
            return Ok(conversation);
        }

        /// <summary>
        /// 获取用户最近的对话列表
        /// </summary>
        [HttpGet("user/{userId}/recent")]
        public async Task<ActionResult<IEnumerable<Conversation>>> GetRecentConversations(
            Guid userId, 
            [FromQuery] int count = 10)
        {
            var conversations = await _conversationService.GetRecentConversationsAsync(userId, count);
            return Ok(conversations);
        }

        /// <summary>
        /// 创建新对话
        /// </summary>
        [HttpPost]
        public async Task<ActionResult<Conversation>> CreateConversation([FromBody] CreateConversationRequest request)
        {
            try
            {
                // 处理标题：如果没有提供标题或标题为空，使用默认值
                string title = string.IsNullOrWhiteSpace(request.Title) ? "新对话" : request.Title.Trim();
                
                // 确保标题不超过16字节
                title = TruncateToBytes(title, 16);
                
                var conversation = await _conversationService.CreateAsync(request.UserId, title);
                return CreatedAtAction(nameof(GetConversation), new { id = conversation.Id }, conversation);
            }
            catch (Exception ex)
            {
                return BadRequest($"创建对话失败: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 截取字符串到指定字节数，确保不会截断多字节字符
        /// </summary>
        private static string TruncateToBytes(string input, int maxBytes)
        {
            if (string.IsNullOrEmpty(input))
                return input;
                
            var encoding = System.Text.Encoding.UTF8;
            var bytes = encoding.GetBytes(input);
            
            if (bytes.Length <= maxBytes)
                return input;
                
            // 逐个减少字节直到找到有效的UTF-8序列
            for (int i = maxBytes; i > 0; i--)
            {
                try
                {
                    var truncatedBytes = new byte[i];
                    Array.Copy(bytes, truncatedBytes, i);
                    var result = encoding.GetString(truncatedBytes);
                    
                    // 验证字符串是否被正确解码（没有乱码）
                    if (encoding.GetBytes(result).Length == i)
                        return result;
                }
                catch
                {
                    continue;
                }
            }
            
            return input.Substring(0, 1); // 最坏情况下返回第一个字符
        }

        /// <summary>
        /// 更新对话信息
        /// </summary>
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateConversation(Guid id, [FromBody] Conversation conversation)
        {
            if (id != conversation.Id)
            {
                return BadRequest("对话ID不匹配");
            }

            try
            {
                await _conversationService.UpdateAsync(conversation);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"更新对话失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 删除对话
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteConversation(Guid id)
        {
            try
            {
                await _conversationService.DeleteAsync(id);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"删除对话失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 向对话添加消息
        /// </summary>
        [HttpPost("{id}/messages")]
        public async Task<IActionResult> AddMessageToConversation(Guid id, [FromBody] Message message)
        {
            try
            {
                await _conversationService.AddMessageAsync(id, message);
                return NoContent();
            }
            catch (Exception ex)
            {
                return BadRequest($"添加消息失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取对话的消息数量
        /// </summary>
        [HttpGet("{id}/message-count")]
        public async Task<ActionResult<int>> GetMessageCount(Guid id)
        {
            try
            {
                var count = await _conversationService.GetMessageCountAsync(id);
                return Ok(count);
            }
            catch (Exception ex)
            {
                return BadRequest($"获取消息数量失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 收藏/取消收藏会话
        /// </summary>
        [HttpPost("{id}/collect")]
        public async Task<IActionResult> SetCollect(Guid id, [FromQuery] bool isCollect)
        {
            await _conversationService.SetCollectAsync(id, isCollect);
            return NoContent();
        }
    }

    // 请求模型
    public class CreateConversationRequest
    {
        public Guid UserId { get; set; }
        public string Title { get; set; } = string.Empty;
    }
}
